package org.mwielocha.jxcube.tasks;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.mwielocha.jxcube.db.Database;
import org.mwielocha.jxcube.ut.Utilities;

public class PopulateTableTask extends AbstractTask {
  
  protected Table table;
  protected String query;
  protected boolean close;

  protected Database db;
  
  public PopulateTableTask(String query, Table table, boolean close) {
    this.table = table;
    this.query = query;
    this.close = close;
  }
  
  @Override
  public void runTask() {
    try {
      
      db = new Database();
      db.open();
      ResultSet rs = db.executeSQL(query);
      
      
  //    Thread.sleep(500);
      
      Display.getDefault().asyncExec(new Runnable() {
        
        @Override
        public void run() {
          table.removeAll();
        }
      });
      
//      Database db = Database.getInstance();
//      db.open();
      
      if(!isRunning()) {
        return;
      }
      
      int columnCount = rs.getMetaData().getColumnCount();
      
      while(rs.next()) {
        
        System.out.println("status: " + getStatus());
        
        if(!isRunning()) {
          System.out.println("breaking!");
          break;
        }
        
        List<String> valuesList = new ArrayList<String>();
        for(int i = 1; i <= columnCount; i++) {
          valuesList.add(rs.getString(i));
        }
        
        final String[] values = valuesList.toArray(new String[] {} );
        
        table.getDisplay().asyncExec(new Runnable() {
          
          @Override
          public void run() {
            if(!isCanceling() && !isCanceled()) {
              TableItem item = new TableItem(table, SWT.NONE);
              item.setText(values);
              table.redraw();
            }
          }
        });    
      
      } 
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println("finished!");
  }
  
  @Override
  public void cleanUp() {
    if(true) {
      try {
        db.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
}
